package com.peanut.huibutie.openapi;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.peanut.huibutie.common.AppConfig;
import com.peanut.huibutie.common.HttpInvoker;
import com.peanut.huibutie.common.OpenApiResult;
import com.peanut.huibutie.common.UserContext;
import com.peanut.huibutie.entity.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 获取收银台URL
 *
 * @see <a href="https://www.showdoc.com.cn/huibutie/10930702197539505">API</a>
 */
@Slf4j
@Service
public class Cashier {
    @Resource
    private HttpInvoker httpInvoker;

    @Resource
    private UserContext userContext;
    @Resource
    private CreateAccessToken createAccessToken;

    public void invoke() {
        OrderVO orderVO = new OrderVO();
        orderVO.setOuterOrderNo("" + System.currentTimeMillis())
                .setOrderAmt(RandomUtil.randomLong(5, 200))
                .setAttach("SDK测试")
                .setNotifyUrl("http://localhost:8081/notify/pay_notify")
                .setOrderTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        String url = invoke(orderVO);
        log.info("调用API获取收银台地址，url={}", url);
    }

    public String invoke(OrderVO orderVO) {
        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
        JSONObject map = (JSONObject) JSONObject.toJSON(orderVO, serializeConfig);
        map.put("open_id", userContext.getContext().getOpenId());
        map.put("access_token", userContext.getContext().getAccessToken());
        map.put("timestamp", System.currentTimeMillis());

        OpenApiResult<JSONObject> openApiResult = httpInvoker.sendPost(AppConfig.Cashier_URL, map, JSONObject.class);

        if (openApiResult.isSuccess()) {
            JSONObject data = openApiResult.getData();
            String url = data.getString("url");
            return url;
        } else if (openApiResult.isAuthError()) {//token校验错误。重新获取token。
            createAccessToken.invoke();
            return invoke(orderVO);
        }else {
            log.info("调用API获取收银台地址时，返回错误：{}", openApiResult);
            return null;
        }
    }
}
